import * as robotModel from '../../models/robot';
import config from '../../config';
import * as rabbitmqHelp from '../../helps/third/rabbitmq';
import { ValidException, EmptyException } from '../../helps/exception';

export function* register({ code }) {
  if (!code) throw ValidException('Code empty');

  let robot = yield robotModel.getByCode(code);
  if (!robot) throw EmptyException('Code invalid');
  yield robot.refreshToken(config.cache.token_expire_seconds);
  let mqtt_username = `robot-${code}`;
  let mqtt_password = String.randomString(16);
  yield rabbitmqHelp.generateAccount(mqtt_username, mqtt_password);
  yield rabbitmqHelp.updateAccountPermissions(mqtt_username, {});
  yield robot.bindMqtt({ mqtt_username, mqtt_password });
  return robot;
}

export function* validToken({ token }) {
  if (!token) throw ValidException('Token empty');
  let robot = yield robotModel.getByToken(token);
  if (!robot) throw EmptyException('Token invalid');
  if (new Date(robot.expire_time) < new Date()) throw ValidException('Token过期, 请刷新token');
  return robot;
}

export function* refreshToken({ refresh_token, robot_id }) {
  if (!refresh_token) throw ValidException('Token empty');
  let robot = yield robotModel.get(robot_id);
  if (!robot) throw EmptyException('Robot not exist');
  if (robot.refresh_token !== refresh_token) throw ValidException('Token invalid');
  yield robot.refreshToken(config.cache.token_expire_seconds);
  return robot;
}
